document.addEventListener('DOMContentLoaded', function () {
  const exportBtn = document.getElementById('exportBtn');
  const importBtn = document.getElementById('importBtn');
  const clearBtn = document.getElementById('clearBtn');
  const storageData = document.getElementById('storageData');
  const sourceUrl = document.getElementById('sourceUrl');
  const storageDataContainer = document.getElementById('storageDataContainer');
  const exportStatus = document.getElementById('exportStatus');
  const importStatus = document.getElementById('importStatus');
  const clearStatus = document.getElementById('clearStatus');

  // 默认隐藏数据区域
  storageDataContainer.style.display = 'none';

  // 显示通知的辅助函数
  function showNotification(title, message) {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'images/icon48.png', // 确保您的扩展中有这个图标
      title: title,
      message: message
    });
  }

  // 从Chrome存储中加载之前的数据
  chrome.storage.local.get(['exportedData'], function (result) {
    if (result.exportedData) {
      storageData.value = JSON.stringify(result.exportedData, null, 2);
      storageDataContainer.style.display = 'block';

      // 显示数据来源网址
      if (result.exportedData.url) {
        sourceUrl.textContent = '数据来源: ' + result.exportedData.url;
        sourceUrl.style.display = 'block';
      }
    }
  });

  // Export localStorage from the current site
  exportBtn.addEventListener('click', async () => {
    try {
      // Query the active tab
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      // Execute script in the current page to get localStorage data
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          try {
            const data = {};
            for (let i = 0; i < localStorage.length; i++) {
              const key = localStorage.key(i);
              data[key] = localStorage.getItem(key);
            }
            return {
              url: window.location.href,
              data: data,
              timestamp: new Date().toISOString()
            };
          } catch (err) {
            return { error: err.message };
          }
        }
      });

      const result = results[0].result;

      if (result.error) {
        exportStatus.textContent = 'Error: ' + result.error;
        exportStatus.className = 'error';
        return;
      }

      storageData.value = JSON.stringify(result, null, 2);
      storageDataContainer.style.display = 'block';

      // 显示数据来源网址
      if (result.url) {
        sourceUrl.textContent = '数据来源: ' + result.url;
        sourceUrl.style.display = 'block';
      }

      // 保存到Chrome存储以便持久化
      chrome.storage.local.set({ exportedData: result }, function () {
        // 显示成功信息
        showNotification('导出成功', '已导出 ' + Object.keys(result.data).length + ' 个项目');
        exportStatus.textContent = '';
      });
    } catch (error) {
      exportStatus.textContent = 'Error: ' + error.message;
      exportStatus.className = 'error';
    }
  });

  // Import localStorage to the current site
  importBtn.addEventListener('click', async () => {
    try {
      let dataToImport;

      try {
        dataToImport = JSON.parse(storageData.value);
      } catch (e) {
        importStatus.textContent = 'Error: Invalid JSON format';
        importStatus.className = 'error';
        return;
      }

      if (!dataToImport || !dataToImport.data) {
        importStatus.textContent = 'Error: Invalid data format';
        importStatus.className = 'error';
        return;
      }

      // Query the active tab
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      // Execute script in the current page to set localStorage data
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: (importData) => {
          try {
            const importedKeys = [];
            for (const [key, value] of Object.entries(importData)) {
              localStorage.setItem(key, value);
              importedKeys.push(key);
            }
            return {
              success: true,
              count: importedKeys.length,
              keys: importedKeys
            };
          } catch (err) {
            return { error: err.message };
          }
        },
        args: [dataToImport.data]
      });

      const result = results[0].result;

      if (result.error) {
        importStatus.textContent = 'Error: ' + result.error;
        importStatus.className = 'error';
        return;
      }

      // 显示成功信息
      showNotification('导入成功', '已导入 ' + result.count + ' 个项目');
      importStatus.textContent = '';

      // 导入成功后清除存储的数据
      chrome.storage.local.remove(['exportedData'], function () {
        // 隐藏数据区域
        storageDataContainer.style.display = 'none';
        sourceUrl.style.display = 'none';
        storageData.value = '';
      });
    } catch (error) {
      importStatus.textContent = 'Error: ' + error.message;
      importStatus.className = 'error';
    }
  });

  // Clear localStorage in the current site
  clearBtn.addEventListener('click', async () => {
    if (!confirm('确定要清除此站点的所有localStorage数据吗？')) {
      return;
    }

    try {
      // Query the active tab
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      // Execute script in the current page to clear localStorage data
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          try {
            const count = localStorage.length;
            localStorage.clear();
            return { success: true, count };
          } catch (err) {
            return { error: err.message };
          }
        }
      });

      const result = results[0].result;

      if (result.error) {
        clearStatus.textContent = 'Error: ' + result.error;
        clearStatus.className = 'error';
        return;
      }

      // 显示成功信息
      showNotification('清除成功', '已清除 ' + result.count + ' 个项目');
      clearStatus.textContent = '';
    } catch (error) {
      clearStatus.textContent = 'Error: ' + error.message;
      clearStatus.className = 'error';
    }
  });
});
